VARIABLES, DATA TYPES, AND TYPE CONVERSION
In Python, variables are used to store data in memory. They act as containers that hold values. Data types define the type of data that can be stored in a variable. Python has several built-in data types, and type conversion allows you to convert data from one type to another.
- Variables: In Python, you can create a variable by giving it a name and assigning a value to it using the assignment operator (
=
). Here's an example:
python
# Creating variables
age = 25
name = "John Doe"
is_student = True
- Data Types: Python has various built-in data types:
- Numeric types:
int
(integers),float
(floating-point numbers), andcomplex
(complex numbers). - Text type:
str
(strings). - Boolean type:
bool
(Boolean values: True or False). - Sequence types:
list
(lists),tuple
(tuples), andrange
(ranges). - Mapping type:
dict
(dictionaries). - Set types:
set
(sets) andfrozenset
(immutable sets). - Binary types:
bytes
andbytearray
. - None type:
None
(a special object representing the absence of a value).
- Type Conversion (Type Casting): Sometimes, you may need to convert data from one type to another. Python allows you to do this using various built-in functions:
int()
: Converts to an integer.float()
: Converts to a floating-point number.str()
: Converts to a string.bool()
: Converts to a Boolean value.list()
: Converts to a list.tuple()
: Converts to a tuple.set()
: Converts to a set.
Here are some examples of type conversion:
python
# Type conversion examples
num_string = "42"
num_int = int(num_string) # Convert the string to an integer
print(num_int) # Output: 42
float_number = 3.14
int_number = int(float_number) # Convert the float to an integer (truncates decimal part)
print(int_number) # Output: 3
bool_value = False
int_value = int(bool_value) # Convert the boolean to an integer (False becomes 0, True becomes 1)
print(int_value) # Output: 0
# Convert a list to a tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
Keep in mind that not all conversions are possible or sensible. For example, converting a string containing letters to an integer will raise a ValueError
. Always make sure the conversion is appropriate for your data.